package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.time.format.DateTimeFormatter;
import java.util.List;

@Controller
public class ResponseEntityUserManagementController {

    @Autowired
    private UserService userService;

    // 使用ResponseEntity明确设置响应头和内容类型
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/response-entity-user-management")
    public ResponseEntity<byte[]> showUserManagementPage(Authentication authentication) {
        // 获取当前登录用户
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);
        
        // 获取所有用户列表
        List<User> users = userService.findAll();
        
        // 创建HTML响应
        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>");
        html.append("<html>");
        html.append("<head>");
        html.append("    <meta charset='UTF-8'>");
        html.append("    <title>用户管理</title>");
        html.append("    <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css'>");
        html.append("</head>");
        html.append("<body>");
        html.append("    <div class='container mt-5'>");
        html.append("        <h2 class='mb-4'>用户管理</h2>");
        
        if (users.isEmpty()) {
            html.append("        <div class='alert alert-info'>暂无用户数据</div>");
        } else {
            html.append("        <table class='table table-striped'>");
            html.append("            <thead>");
            html.append("                <tr>");
            html.append("                    <th>用户名</th>");
            html.append("                    <th>邮箱</th>");
            html.append("                    <th>注册时间</th>");
            html.append("                    <th>状态</th>");
            html.append("                </tr>");
            html.append("            </thead>");
            html.append("            <tbody>");
            
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            
            for (User user : users) {
                html.append("                <tr>");
                html.append("                    <td>").append(user.getUsername()).append("</td>");
                html.append("                    <td>").append(user.getEmail()).append("</td>");
                html.append("                    <td>").append(user.getCreateTime().format(formatter)).append("</td>");
                html.append("                    <td>").append(user.getStatus() == 1 ? "活跃" : "禁用").append("</td>");
                html.append("                </tr>");
            }
            
            html.append("            </tbody>");
            html.append("        </table>");
        }
        
        html.append("    </div>");
        html.append("</body>");
        html.append("</html>");
        
        // 创建响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_HTML);
        headers.setContentLength(html.toString().getBytes().length);
        
        // 使用ResponseEntity返回响应
        return new ResponseEntity<>(html.toString().getBytes(), headers, HttpStatus.OK);
    }
    
    // 更新用户状态
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/response-entity-user/update-status")
    public String updateUserStatus(@RequestParam("userId") Long userId, @RequestParam("status") Integer status) {
        userService.updateStatus(userId, status);
        return "redirect:/response-entity-user-management";
    }
    
    // 删除用户
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/response-entity-user/delete")
    public String deleteUser(@RequestParam("userId") Long userId, RedirectAttributes redirectAttributes) {
        userService.delete(userId);
        redirectAttributes.addFlashAttribute("message", "用户已成功删除");
        return "redirect:/response-entity-user-management";
    }
}